package com.neu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.common.exception.NoStockException;
import com.neu.common.to.SkuHasStockVo;
import com.neu.common.to.mq.OrderTo;
import com.neu.common.to.mq.StockDetailTo;
import com.neu.common.to.mq.StockLockedTo;
import com.neu.common.utils.PageUtils;
import com.neu.common.utils.Query;
import com.neu.common.utils.R;
import com.neu.gulimall.ware.dao.WareSkuDao;
import com.neu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.neu.gulimall.ware.entity.WareOrderTaskEntity;
import com.neu.gulimall.ware.entity.WareSkuEntity;
import com.neu.gulimall.ware.feign.MemberFeignService;
import com.neu.gulimall.ware.feign.OrderFeignService;
import com.neu.gulimall.ware.feign.ProductFeignService;
import com.neu.gulimall.ware.service.WareOrderTaskDetailService;
import com.neu.gulimall.ware.service.WareOrderTaskService;
import com.neu.gulimall.ware.service.WareSkuService;
import com.neu.gulimall.ware.vo.OrderItemVo;
import com.neu.gulimall.ware.vo.OrderVo;
import com.neu.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    /**
     * 库存自动解锁
     *    下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，但库存不能回滚，此时之前锁定的库存就要自动解锁，以达到最终一致性的目的。
     *    此时库存工作单信息还在，并且已经发送到了MQ中，可以根据消息来解锁库存
     *
     * 只要 解锁库存的消息失败，一定要告诉服务解锁失败
     *
     * @param message
     * @param to
     */


    /**
     * 解锁库存的方法
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    public void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId) {

        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,num);

        //更新工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        //变为已解锁
        taskDetailEntity.setLockStatus(2);
        orderTaskDetailService.updateById(taskDetailEntity);

    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        // http://localhost:88/api/ware/waresku/list?t=1655278197799&page=1&limit=10&skuId=1&wareId=2
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");

        if (StringUtils.isNotEmpty(skuId)) {
            queryWrapper.eq("sku_id",skuId);
        }

        if (StringUtils.isNotEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        //1、判断如果没有这个库存记录新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(
                new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败整个事务无需回滚
            //1、自己catch异常
            try{
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            //添加库存信息
            wareSkuDao.insert(wareSkuEntity);
        } else {
            //修改库存信息
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> list = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null?false:count > 0);

            return vo;
        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 为某个订单锁定库存
     *
     * 库存解锁的场景：
     *  1、下订单成功，订单过期没有支付被系统自动取消、被用户手动取消，此时都要解锁库存
     *  2、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，但库存不能回滚，此时之前锁定的库存就要自动解锁，以达到最终一致性的目的
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单详情信息
         * 追溯
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        orderTaskService.save(wareOrderTaskEntity);


        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //2、找到每个商品在哪个仓库都有库存
        // 将要锁定的商品项
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map((item) -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIdList);

            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();

            if (org.springframework.util.StringUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }

            // 1、如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给MQ
            // 2、锁定失败，前面保存的工作单信息就回滚了，发送出去的消息，即使要解锁记录，由于去数据库中查不到id，所以就不能解锁了
            for (Long wareId : wareIds) {
                //锁定成功就返回1，失败就返回0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    // 锁定成功
                    skuStocked = true;

                    //TODO 告诉MQ库存锁定成功，以便出现异常时能够解锁
                    WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                            .skuId(skuId)
                            .skuName("")
                            .skuNum(hasStock.getNum())
                            .taskId(wareOrderTaskEntity.getId())
                            .wareId(wareId)
                            .lockStatus(1)
                            .build();
                    orderTaskDetailService.save(taskDetailEntity);

                    // 发消息给MQ  锁定成功一个，就发一个消息给 MQ
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,detailTo);
                    lockedTo.setDetailTo(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);

                    break;
                }else {
                    // 当前仓库锁失败，重试下一个仓库
                }
            }

            if (skuStocked == false) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        //3、肯定全部都是锁定成功的
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        // MQ消息发过来的数据
        StockDetailTo detailTo = to.getDetailTo(); // 库存工作项的详细信息
        Long detailToId = detailTo.getId(); // 库存工作项的id

        // 根据MQ消息发过来的数据判断是否解锁
        WareOrderTaskDetailEntity taskDetailEntity = orderTaskDetailService.getById(detailToId);
        if (taskDetailEntity != null){
            // 说明不是 锁定库存时出现异常，导致的回滚，是在下单业务中调用锁定库存远程调用成功之后，出现的其他业务异常，导致的回滚
            // 有，证明了 库存锁定成功，库存业务没有问题
            // 但是 是否需要解锁，还需要查看订单情况
            /*
                  根据订单序列号查询数据库，如果没有这个订单，说明订单回滚了，必须解锁
                                 如果有这个订单，根据订单的状态来判断，订单状态是已取消，就解锁库存，没取消就不能解锁
             */
            Long id = to.getId(); // 库存工作单的id
            // 根据  库存工作单的id 中去查到库存工作单的详细信息
            WareOrderTaskEntity orderTaskEntity = orderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn(); // 获取订单的序列号
            R r = orderFeignService.getOrderStatus(orderSn);
            //远程查询订单信息
            if (r.getCode() == 0){
                // 订单数据返回成功
                OrderVo data = r.getData("data",new TypeReference<OrderVo>() {
                });
                //判断订单状态是否已取消或者支付或者订单不存在
                if (data == null || data.getStatus() == 4){
                    // 订单不存在     库存工作单中的订单序列号在订单表中一定要有相同的订单序列号，否则就是有问题
                    //订单已被取消，才能解锁库存
                    if (taskDetailEntity.getLockStatus() == 1) {
                        //当前库存工作单详情状态1，已锁定，但是未解锁才可以解锁
                        unLockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),detailToId);
                    }

                }
            }else {
                //消息拒绝以后重新放在队列里面，让别人继续消费解锁
                //远程调用服务失败
                throw new RuntimeException("远程调用服务失败");
            }

        }else {
            //无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     * @param orderTo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlockStock(OrderTo orderTo) {

        String orderSn = orderTo.getOrderSn();
        //查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);

        //按照工作单的id找到所有 没有解锁的库存，进行解锁
        Long id = orderTaskEntity.getId(); // 库存工作单id
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id).eq("lock_status", 1));

        if (list != null && list.size() > 0){
            for (WareOrderTaskDetailEntity taskDetailEntity : list) {
                unLockStock(taskDetailEntity.getSkuId(),
                        taskDetailEntity.getWareId(),
                        taskDetailEntity.getSkuNum(),
                        taskDetailEntity.getId());
            }
        }


    }


    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}